from skyfield.api import load, Topos
from datetime import datetime, timedelta
import pytz


def python_function(str1, str2, str3,num):
    # 下载最新的 TLE 数据
    stations_url = 'https://celestrak.org/NORAD/elements/stations.txt'
    print('正在下载 TLE 数据...')
    satellites = load.tle_file(stations_url)
    print('TLE 文件已下载')

    # 提取 ISS (ZARYA)
    print(f'提取{str3}卫星数据...')
    by_name = {sat.name: sat for sat in satellites}
    iss = by_name.get(str3)
    if iss:
        print(f'成功找到{str3}卫星数据。')
    else:
        print(f'未找到{str3}卫星数据，请检查 TLE 数据文件。')
        exit()

    # 设置观测地点（郑州）
    zhengzhou = Topos(str1, str2)
    print(f'观测地点已设置为：{str1}, {str2}')
    #print('观测地点已设置为：（34.8159 N, 113.5810 E）')

    # 获取当前时间和未来48小时的时间范围
    ts = load.timescale()
    t0 = ts.now()
    t1 = ts.utc(t0.utc_datetime().year, t0.utc_datetime().month, t0.utc_datetime().day + 2)

    print('计算过境时间...')
    # 计算过境时间
    t, events = iss.find_events(zhengzhou, t0, t1, altitude_degrees=num)

    # 设置时区为北京时间
    cst = pytz.timezone('Asia/Shanghai')
    results = []
    # 输出结果
    if len(t) > 0 and len(events) > 0:
        for ti, event in zip(t, events):
            name = ('升起', '最高点', '落下')[event]
            local_time = ti.utc_datetime().replace(tzinfo=pytz.utc).astimezone(cst)
            results.append((local_time.strftime('%Y-%m-%d %H:%M:%S'), name))
            #print(f'{local_time:%Y-%m-%d %H:%M:%S} CST - {name}')
    else:
        print('未来48小时内无过境事件。')
    return results


